  <template>
    <s-layout title="销售订单">
      <su-sticky bgColor="#fff">
        <su-tabs :list="tabMaps" :scrollable="false" @change="onTabsChange" :current="state.currentTab" />
      </su-sticky> 
      <!-- 查询条件 -->
      <view class="filters">
        <view @click="toggleFilters" class="filter-header">
          <text>查询条件</text>
          <text>{{ state.showFilters ? '收起' : '展开' }}</text>
        </view>
        <view v-show="state.showFilters" class="filter-body">
          <input class="filter-input" v-model="query.name" placeholder="请输入关键字" />
          <input class="filter-input" v-model="query.no" placeholder="请输入订单单号" />
          
		  <picker class="filter-input" mode="selector" :range="customerNames" @change="onCustomerChange" :value="state.customerIndex">
		      <view class="pickercustomer">{{ customerNames[state.customerIndex] || '请选择客户' }}</view>
		  </picker>
          <view class="item-actions-inline">
            <button @click="search" class="action-button">查询</button>
            <button @click="reset" class="action-button danger">重置</button>
          </view>
        </view>
      </view>
	   <!-- 悬浮按钮 -->
	   <uni-fab
			ref="fabRef"
			horizontal="right"
			vertical="bottom" 
			@fabClick="goAdd" 
	   /> 
      <!-- 订单列表 -->
      <s-empty v-if="state.pagination.total === 0" icon="/static/order-empty.png" text="暂无订单" />
      <view v-if="state.pagination.total > 0">
        <view v-for="item in state.pagination.list" :key="item.id" class="bg-white order-list-card-box ss-r-10 ss-m-t-14 ss-m-20">
          <view @click="viewDetails(item)">
            <view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20">
              <view class="order-no">编号：{{ item.no }}</view>
              <text :class="['status-badge', getStatusClass(item.status)]">{{ getStatusText(item.status) }}</text>
            </view>
            <view class="ss-p-x-20">
              <view>客户：{{ item.customerName }}</view>
              <view>产品：{{ item.productNames }}</view>
              <view>订单时间：{{ item.orderTime }}</view>
              <view>总数量：{{ item.totalCount }}</view>
              <view>出库数：{{ item.outCount }}</view>
              <view>金额：￥{{ item.totalProductPrice }}</view>
              <view>退货数：{{ item.returnCount }}</view>
            </view>
          </view>
          <view class="pay-box ss-flex ss-row-right ss-p-r-20">
            <view class="ss-flex ss-col-center">
              <view class="discounts-title pay-color">总金额:</view>
              <view class="discounts-money pay-color">￥{{ item.totalProductPrice }}</view>
            </view>
          </view>
          <view class="order-card-footer ss-m-t-30 ss-flex ss-col-center ss-p-x-20">
            <button @click="editItem(item)" class="action-button">出库</button>
            <button @click="editItem(item)" class="action-button">开票</button>
            <button @click="editItem(item)" class="action-button">付款</button>
            <button @click="updateStatus(item.id, '20')" class="action-button">审核</button>
            <button @click="updateStatus(item.id, '10')" class="action-button">反审核</button>
            <button @click="editItem(item)" class="action-button">修改</button>
            <button @click="deleteItem(item)" class="action-button danger">删除</button>
          </view>
          <view class="divider"></view>
        </view>
      </view>
  
      <!-- 加载更多 -->
      <uni-load-more
        v-if="state.pagination.total > 0"
        :status="state.loadStatus"
        :content-text="{ contentdown: '上拉加载更多' }"
        @tap="loadMore"
      />
    </s-layout>
  </template>
<script setup>
	import { reactive, computed } from 'vue';
	import { onLoad,onShow, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
	import { getCustomers, pageList, deleteOrders, updateSaleOrderStatus } from "@/sheep/api/erp/order.js";
	import { resetPagination } from '@/sheep/util';
	import sheep from '@/sheep';
	// 数据状态
	const state = reactive({
	  currentTab: 0,
	  showFilters: false,
	  customers: [],
	  customerIndex: -1,
	  pagination: {
		list: [],
		total: 0,
		pageNo: 1,
		pageSize: 5,
	  },
	  loadStatus: '' 
	});

	const query = reactive({
	  name: '',
	  no: '',
	  customerId: '',
	  remark: '',
	});

	// 计算属性，用于提供客户名称列表
	const customerNames = computed(() => state.customers.map(customer => customer.name));

	const tabMaps = [
	  { id: 10, name: '未审核' },
	  { id: 20, name: '已审核' },
	  { id: 30, name: '待发货' },
	  { id: 40, name: '已发货' },
	  { id: 50, name: '待付款' },
	  { id: 60, name: '已付款' },
	];

	function getStatusClass(status) {
	  const statusMap = {
		10: 'unaudited',
		20: 'audited',
		30: 'unshipped',
		40: 'shipped',
		50: 'unpaid',
		60: 'paid'
	  };
	  return statusMap[status] || '';
	};

	function getStatusText(status) {
	  const statusTextMap = {
		10: '未审核',
		20: '已审核',
		30: '待发货',
		40: '已发货',
		50: '待付款',
		60: '已付款'
	  };
	  return statusTextMap[status] || '未知状态';
	};

	async function fetchCustomers() {
	  try {
		const res = await getCustomers();
		state.customers = res.data;
	  } catch (error) {
		console.error("Failed to fetch customers", error);
	  }
	}

	function onTabsChange(e) {
	  if (state.currentTab === e.index) {
		return;
	  }
	  resetPagination(state.pagination);
	  state.currentTab = e.index;
	  getOrderList(true);
	};

	function toggleFilters() {
	  state.showFilters = !state.showFilters;
	};

	function onCustomerChange(e) {
	  state.customerIndex = parseInt(e.detail.value, 10);
	  if (state.customerIndex !== -1) {
		query.customerId = state.customers[state.customerIndex].id;
	  } else {
		query.customerId = ''; // 如果用户取消选择，则清空 customerId
	  }
	};
	function goAdd(e) { 
		uni.navigateTo({
		  url: '/pages/erp/sale/edit'
		}); 
	}
	 
	 function editItem(item) {
		 sheep.$router.go('/pages/erp/sale/edit', {
		   orderId: item.id,
		 }); 
	 };

	function viewDetails(item) {
	  uni.navigateTo({
		url: "/pages/erp/sale/show?orderId=" + encodeURIComponent(item.id)
	  });
	};

	async function updateStatus(id, status) {
	  try {
		await updateSaleOrderStatus(id, status);
		sheep.$helper.toast(`审核成功`);
		search(); // 更新状态后重新搜索
	  } catch (error) {
		console.error("Failed to update order status", error);
	  }
	};

	async function deleteItem(item) {
	  try {
		await deleteOrders(item.id);
		sheep.$helper.toast(`删除成功`);
		search(); // 删除订单后重新搜索
	  } catch (error) {
		console.error("Failed to delete order", error);
	  }
	};


	function reset() {
	  Object.assign(query, { name: '', no: '', customerId: '', remark: '' });
	  state.customerIndex = -1; // 确保客户选择也被重置
	  state.pagination.pageNo = 1;
	  state.pagination.list = [];
	  getOrderList(true);
	}

	function search() {
	  state.pagination.pageNo = 1;
	  state.pagination.list = []; // 清空现有列表
	  getOrderList(true);
	}

	async function getOrderList(isRefresh = false) {
	  state.loadStatus = 'loading';
	  const params = { status: tabMaps[state.currentTab].id, ...query, pageNo: state.pagination.pageNo, pageSize: state.pagination.pageSize };

	  try {
		const { code, data } = await pageList(params);
		if (code !== 0) return;

		if (isRefresh) state.pagination.list = data.list;
		else state.pagination.list = [...state.pagination.list, ...data.list];

		state.pagination.total = data.total;
		state.loadStatus = state.pagination.list.length < state.pagination.total ? 'more' : 'noMore';
	  } catch (error) {
		state.loadStatus = 'error';
		console.error(error);
	  }
	}
	onShow(() => {
		console.log('onShow');
	});
	onLoad(async (options) => {
	  if (options.type) {
		state.currentTab = options.type;
	  }
	  await fetchCustomers(); // 先加载客户列表
	  await getOrderList(); // 再加载订单列表
	});

	function loadMore() {
	  if (state.loadStatus === 'noMore') {
		return;
	  }
	  state.pagination.pageNo++;
	  getOrderList();
	}

	onReachBottom(() => {
	  loadMore();
	});

	onPullDownRefresh(async () => {
	  resetPagination(state.pagination);
	  await getOrderList(true);
	  uni.stopPullDownRefresh();
	});	
</script>
<style scoped>
.filters {
  margin: 5px;
  background-color: #fff;
  border-radius: 5px;
  padding: 8px;
}
.filter-header {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #333;
}
.filter-body {
  margin-top: 10px;
}
.filter-input {
  width: 100%;
  height: 50rpx;
  padding: 3px;
  font-size: 14px;
  margin-bottom: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
.item-actions-inline {
  display: flex;
  justify-content: flex-start;
  gap: 5px;
}
.action-button {
  height: 25px;
  width: 45px;
  line-height: 25px;
  text-align: center;
  font-size: 14px;
  border-radius: 3px;
  background-color: #2e70fc;
  color: #fff;
  border: none;
  cursor: pointer;
  padding: 1px 3px;
}
.danger {
  background-color: red;
}
.order-card-header {
  height: 80rpx;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.status-badge {
  width: 50px;
  height: 25px;
  text-align: center;
  line-height: 25px;
  font-size: 12px;
  color: #fff;
  font-weight: bold;
}
.status-badge.unaudited {
  background-color: #2e70fc;
}
.status-badge.audited {
  background-color: #00c300;
}
.order-list-container {
  height: calc(100vh - 100px);
  overflow-y: auto;
}
</style>